﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LGSVR.Common;
using System.Data;
using LGSVR.BLL.Sys;
using LGSVR.BLL.Program;

namespace LGSVR_WEB.program
{
    public partial class messageInfoEdit : DataBasePage
    {
        int _pid;
        private int Pid
        {
            get
            {
                return string.IsNullOrEmpty(Request.QueryString["ID"]) ? 0 : int.Parse(Request.QueryString["ID"]);
            }
            set
            {
                _pid = value;
                //Pid = _pid;
            }
        }
       
        private string cardID
        {
            get
            {
                return string.IsNullOrEmpty(Request.QueryString["cardID"]) ? "0" : Request.QueryString["cardID"];
            }
            
        }
        MessageInfo msgInfo = new MessageInfo();
        protected string strAction;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserID"] == null)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "out", "<script>alert('系统超时或服务器故障，请退出重新登录！');window.parent.parent.navigate('../Logout.aspx');</script>");
            }
            if (!IsPostBack)
            {
                //BinddllList(ddlgroupID, "messageGroup", "GroupName", "messageGroupID", "", "ID");  //节目组下拉绑定
                innit();
               
            }
        }


        private void innit()
        {
            BinddllList(ddlgroupID, "messageGroup", "GroupName", "messageGroupID", "", "ID");  //节目组下拉绑定
            
            
            //只有管理员和超级管理员才能看到即时信息
            if (Session["actID"] != null)
            {
                MessageInfo msgInfo = new MessageInfo();
                //只能通过角色名称判断，因为ID不确定
                string _ActName = msgInfo.GetstrValue("SELECT ActName  FROM userAct WHERE actID = " + Session["actID"]);
                if((!_ActName.Contains("管理员")) && ddlgroupID.Items.Contains(ddlgroupID.Items.FindByText("即时信息")))
                {
                 ddlgroupID.Items.Remove(ddlgroupID.Items.FindByText("即时信息")); //按显示文本删除     
                }
            }
            BinddllList(ddlareaID, "cardGroupArea", "areaID", "areaID", "", "ID");  //卡分区
            //BinddllList(ddlareaID,"cardGroupArea", "GroupName", "messageGroupID"," groupID in (select groupID from where cardID = '" + cardID + "') ", "grade");  //卡分区
            //BinddllList(ddlcompanyID, "company", "companyName", "companyID", "", "ID");  //公司下拉绑定
            bool isSupperAdmin = Session["ActName"].ToString() == "超级管理员";
            string strWhere = string.Empty;
            if (!isSupperAdmin)
            {
                strWhere += " and companyid='" + Session["CompanyID"] + "'";
            }
            BinddllList(ddlcompanyID, "company", "companyName", "companyID", strWhere, "ID");  //公司下拉绑定


            //控制卡配置 里面的actCount节目总数是通用？没看到与信息卡对应啊。
            BindactdllList();//节目编号下拉绑定

            //txtStartTime.Attributes.Add("readonly", "readonly");
            //txtEndTime.Attributes.Add("readonly", "readonly");
            BindConfigList(ddlinType, "MSG_IN_TYPE");//进入方式绑定
            BindConfigList(ddloutType, "MSG_OUT_TYPE");//退出方式绑定
            Dictionary<string, string> dicSingle;
            // 编辑
            if (!string.IsNullOrEmpty(Request.QueryString["action"]) && Request.QueryString["action"].ToLower() == "edit")
            {
                btnSave.Text = "更 新";
                if (Pid != 0)
                {
                    dicSingle = GetSigle("messageInfo", "ID=" + Pid);

                    if (dicSingle != null)
                    {
                        ddlgroupID.SelectedValue = dicSingle["groupID"];
                        ddlareaID.SelectedValue = dicSingle["areaID"];
                        ddlcompanyID.SelectedValue = dicSingle["companyID"];


                        txtmessageTitle.Text = dicSingle["messageTitle"];
                        //ddlactID.Items.Add(new ListItem(dicSingle["actID"].ToString(), dicSingle["actID"].ToString()));
                        ddlactID.SelectedValue = dicSingle["actID"];
                        ddlactID.Enabled = false;

                        txtpixWidth.Text = dicSingle["pixWidth"];
                        ddlinType.SelectedValue = dicSingle["inType"];
                        ddloutType.SelectedValue = dicSingle["outType"];
                        txtoutSpeed.Text = dicSingle["outSpeed"];


                        txtstayTime.Text = dicSingle["stayTime"];
                        txtreplayTimes.Text = dicSingle["replayTimes"];

                        txtBeginTime.Value = dicSingle["BeginTime"];
                        txtEndTime.Value = dicSingle["EndTime"];


                        txtmessageTxt.Text = dicSingle["messageTxt"];
                        txtcontent.Text = dicSingle["content"];

                     
                    }
                    else
                    {
                        MsgContent = ShowMessage("数据加载失败。", MessageType.Error, true, false);
                    }
                }
            }
          
        }

        private static void BindConfigList(DropDownList ddlList, string strspama)
        {
            ParamList parm = new ParamList();
            ddlList.DataSource = parm.GetListByBelong(strspama);
            ddlList.DataTextField = "typename";
            ddlList.DataValueField = "ID";
            ddlList.DataBind();
        }

        

        private void BindactdllList()
        {

            int intstart = 1;           
            int intactid = msgInfo.GetintValue("SELECT MAX(actCount) as actCount  FROM configInfo");
            if (ddlgroupID.SelectedItem.Text == "即时信息" || ddlgroupID.SelectedValue == "JSXX")
                intstart = intactid - 6;
            ddlactID.Items.Clear();
                 //得到有权限的卡号取值区间    
            int _beginActID = msgInfo.GetintValue("SELECT beginActID  FROM userCardGroup A,cardinfo B WHERE A.state ='1' AND userID = '" + Session["userID"] + "' AND A.CardGroupID = B.GroupID AND B.cardID = '" + Request["cardID"] + "'");
            int _endActID = msgInfo.GetintValue("SELECT endActID  FROM userCardGroup A,cardinfo B WHERE A.state ='1' AND userID = '" + Session["userID"] + "' AND A.CardGroupID = B.GroupID AND B.cardID = '" + Request["cardID"] + "'");
            intstart = intstart <= _beginActID ? _beginActID : intstart;//起始时间取大的
            intactid = intactid <= _endActID ? intactid : _endActID;//起始时间取小的
            for (int i = intstart; i <= intactid; i++)
            {
                ddlactID.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
        }

        private void BinddllList(DropDownList ddlList, string strTableName,string strText,string strValue, string strWhere, string strSort)
        {
            DataTable dt;
            int totalRS;

            dt = GetList(strTableName,  strSort + " desc ", strWhere, 1, int.MaxValue, out totalRS);
            ddlList.DataSource = dt;
            ddlList.DataTextField = strText;
            ddlList.DataValueField = strValue;
            ddlList.DataBind();

            ddlList.Items.Insert(0, new ListItem("-请选择-", ""));
        }

        //private void BinddllList()
        //{
        //    DataTable dt;
        //    int totalRS;

        //    dt = GetList("messageGroup", " grade desc ", "", 1, 1000, out totalRS);
        //    ddlgroupID.DataSource = dt;
        //    ddlgroupID.DataTextField = "GroupName";
        //    ddlgroupID.DataValueField = "messageGroupID";
        //    ddlgroupID.DataBind();

        //    ddlgroupID.Items.Insert(0, new ListItem("-请选择-", ""));
        //}
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (HasKey("messageInfo", "actID", ddlactID.SelectedValue, Pid))
            {
                //MsgContent = ShowMessage("已存在该节目编号，请更换！", MessageType.Error, false, true);
                //return;
                //判断该记录是否已经审批
                string strmgsState = msgInfo.GetstrValue("SELECT msgState FROM VmessageInfo WHERE ID = " + Request["chkId"]);
                if (strmgsState == "N")
                {
                    //弹出confirm    
                    ClientScript.RegisterStartupScript(GetType(), "confirm", "CustomSubmit();", true);
                }
                else
                {
                    MsgContent = ShowMessage("对不起，已经审批的节目信息不能再修改。", MessageType.Error, false, true);
                }
            }
            else
            {
                SaveInfo();
            }
        }
        ////确认时执行的代码  
        protected void btnretSave_Click(object sender, EventArgs e)
        {           
            int _pid = msgInfo.GetintValue("SELECT id  FROM messageInfo WHERE actID = '" + ddlactID.SelectedValue + "'");
            
            Dictionary<string, string> dicParam;
            Dictionary<string, string> dicmessageCard;
            SetValue(out dicParam, out dicmessageCard);

            if (_pid != 0)
                {
                    Edit("messageInfo", dicParam, "ID=" + _pid);
                    int totalRS;
                    DataTable dt = GetList("messageInfo", " ID desc ", " AND ID=" + _pid, 1, 10, out totalRS);
                    string strmessageID = dt.Rows[0]["messageID"].ToString();
                    if (Result > 0)
                    {
                        Edit("messageCard", dicmessageCard, "messageID=" + strmessageID);
                        if (Result > 0)
                        {
                            MsgContent = ShowMessage("恭喜您，覆写成功！", MessageType.Success, false, true);
                            NoRefresh();
                            return;
                        }
                    }
                   
                    if (Result == -100)
                    {
                        MsgContent = ShowMessage("对不起，操作失败，程序参数异常。", MessageType.Error, false, true);
                    }
                    else
                    {
                        MsgContent = ShowMessage("对不起,操作失败，请重试。", MessageType.Error, false, true);
                    }
                   
                }
           
        }
            
       
            
       
        //保存信息
        private void SaveInfo()
        {
            Dictionary<string, string> dicParam;
            Dictionary<string, string> dicmessageCard;
            SetValue(out dicParam, out dicmessageCard);

            // 编辑
            if ((!string.IsNullOrEmpty(Request.QueryString["action"]) && Request.QueryString["action"].ToLower() == "edit") || !string.IsNullOrEmpty(strAction))
            {
                //即时信息不可编辑
                if (ddlgroupID.SelectedItem.Text == "即时信息")
                {
                    MsgContent = ShowMessage("对不起，即时信息不可修改。", MessageType.Error, false, true);
                }                  
                else
                {
                    if (Pid != 0)
                    {
                        Edit("messageInfo", dicParam, "ID=" + Pid);
                        int totalRS;
                        DataTable dt = GetList("messageInfo", " ID desc ", " AND ID=" + Pid, 1, 10, out totalRS);
                        string strmessageID = dt.Rows[0]["messageID"].ToString();
                        if (Result > 0)
                        {
                            Edit("messageCard", dicmessageCard, "messageID=" + strmessageID);
                            if (Result > 0)
                            {
                                MsgContent = ShowMessage("恭喜您，更新成功！", MessageType.Success, false, true);
                                NoRefresh();
                                return;
                            }
                        }
                        //else
                        //{
                        if (Result == -100)
                        {
                            MsgContent = ShowMessage("对不起，操作失败，程序参数异常。", MessageType.Error, false, true);
                        }
                        else
                        {
                            MsgContent = ShowMessage("对不起,操作失败，请重试。", MessageType.Error, false, true);
                        }
                        //}
                    }
                }
            }
            else  // 新增
            {                

                //Random rd = new Random();
                //string strmessageID = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + rd.Next(100);
                string strmonth = ("0" + DateTime.Now.Month.ToString()).Substring(DateTime.Now.Month.ToString().Length - 1, 2);
                string strDay = ("0" + DateTime.Now.Day.ToString()).Substring(DateTime.Now.Day.ToString().Length - 1, 2);
                int intmessageID = msgInfo.GetintValue("SELECT MAX(messageID) as messageID  FROM messageInfo WHERE messageID LIKE '" + DateTime.Now.Year.ToString() + strmonth + strDay + "%'");
                if (intmessageID >= 99)
                {
                    MsgContent = ShowMessage("当天信息添加数已达99条,请明天再试.", MessageType.Error, false, true);
                }
                else
                {
                    string strRandom = ("0" + (intmessageID + 1)).Substring((intmessageID + 1).ToString().Length - 1, 2);
                    string strmessageID = DateTime.Now.Year.ToString() + strmonth + strDay + strRandom;
                    dicParam.Add("messageID", strmessageID);
                    dicmessageCard.Add("messageID", strmessageID);//信息号

                    Insert("messageInfo", dicParam);

                    if (Result > 0)
                    {
                        Insert("messageCard", dicmessageCard);
                        if (Result > 0)
                        {
                            MsgContent = ShowMessage("恭喜您，添加成功！", MessageType.Success, false, true);
                            NoRefresh();
                            //return;
                        }
                        else
                        {
                            MsgContent = ShowMessage("对不起,操作失败，请重试。", MessageType.Error, false, true);
                        }
                    }
                    else
                    {
                        MsgContent = ShowMessage("对不起,操作失败，请重试。", MessageType.Error, false, true);
                    }
                }
            }
        }

        private void SetValue(out Dictionary<string, string> dicParam, out Dictionary<string, string> dicmessageCard)
        {


            dicParam = new Dictionary<string, string>();


            dicParam.Add("groupID", ddlgroupID.SelectedValue);

            dicParam.Add("areaID", ddlareaID.SelectedValue);
            dicParam.Add("companyID", ddlcompanyID.SelectedValue);


            dicParam.Add("messageTitle", txtmessageTitle.Text.Trim());
            dicParam.Add("actID", ddlactID.SelectedValue);


            dicParam.Add("pixWidth", txtpixWidth.Text.Trim());
            dicParam.Add("inType", ddlinType.SelectedValue);


            dicParam.Add("outType", ddloutType.SelectedValue);
            dicParam.Add("outSpeed", txtoutSpeed.Text.Trim());


            dicParam.Add("stayTime", txtstayTime.Text.Trim());
            dicParam.Add("replayTimes", txtreplayTimes.Text.Trim());

            dicParam.Add("BeginTime", txtBeginTime.Value.Trim());
            dicParam.Add("EndTime", txtEndTime.Value.Trim());


            dicParam.Add("messageTxt", txtmessageTxt.Text.Trim());
            dicParam.Add("content", txtcontent.Text.Trim());

            dicParam.Add("state", "1");

            dicmessageCard = new Dictionary<string, string>();

            //dicmessageCard.Add("groupID", ddlgroupID.SelectedValue);//
            dicmessageCard.Add("cardID", cardID.ToString());//控制卡
            dicmessageCard.Add("userAdd", Session["UserID"].ToString());//添加人员
            dicmessageCard.Add("addTime", DateTime.Now.ToShortDateString());//添加时间
            dicmessageCard.Add("LastSendTime", txtLastSendTime.Value);
            dicmessageCard.Add("SendTimes", txtSendTimes.Text.Trim());
            dicmessageCard.Add("state", "N");
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            //防止卡信息丢失
            //if(cardID =="0")
            //{
            // MessageInfo msgInfo = new MessageInfo(); 
            //     string _State = msgInfo.GetstrValue("SELECT State  FROM messageCard WHERE messageID = " + _messageID);
            //}
            if (!string.IsNullOrEmpty(Request.QueryString["backUrlParam"]))
            {
                Response.Redirect("messageInfoMain.aspx?" + Request.QueryString["backUrlParam"] + "&cardID=" + cardID, false);
            }
            else
            {
                Response.Redirect("messageInfoMain.aspx?cardID=" + cardID, false);
            }
           
        }

        protected void ddlgroupID_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindactdllList();
        }
    }
}